GameplaySceneCaptureSystem框架

RenderTarget、捕获会话与输出 Consumer 具有不同生命周期。RT 已分配不代表首帧可用,Consumer 退出也不自动表示底层渲染缓存已释放。

GameplaySceneCaptureSystem 用 Session 描述一次激活,用 Channel 管理输出和缓存,Manager 统一执行预算调度,Consumer 订阅状态并展示结果。

基础架构

图中按职责分组列出核心类;+、-、# 表示公开、私有和受保护成员。字段类型保留容器与指针语义,TMap 的键和值用 | 分隔,分组不代表额外的源码命名空间。

%%{init: {"class": {"useMaxWidth": false}, "flowchart": {"useMaxWidth": false}}}%%
classDiagram
    direction LR

    namespace System {
        class UGameplaySceneCaptureManager
    }

    namespace Session {
        class FGameplaySceneCaptureSession
    }

    namespace Output {
        class FGameplaySceneCaptureChannelKey
        class FGameplaySceneCaptureChannel
    }

    UGameplaySceneCaptureManager *-- FGameplaySceneCaptureSession : Sessions
    UGameplaySceneCaptureManager *-- FGameplaySceneCaptureChannel : Channels
    FGameplaySceneCaptureSession *-- FGameplaySceneCaptureChannelKey : ChannelKey
    FGameplaySceneCaptureChannel --> FGameplaySceneCaptureSession : ActiveHandle

    class UGameplaySceneCaptureManager {
        - Sessions : TArray~FGameplaySceneCaptureSession~
        - Channels : TMap~FGameplaySceneCaptureChannelKey|FGameplaySceneCaptureChannel~
        - FreeSessionSlots : TArray~int32~
        - NextSerial : int32
        + TryActivateCapture(Owner, CaptureKey, ViewingPlayer, Binding, Options, RuntimeOptions, OutHandle, OutFailureReason) bool
        + DeactivateCapture(Handle, StopReason) bool
        + RequestCaptureFrame(Handle) bool
        - ProcessDueCaptures(NowSeconds)
    }

    class FGameplaySceneCaptureSession {
        + Handle : FGameplaySceneCaptureHandle
        + Owner : TWeakObjectPtr~UObject~
        + ViewingPlayer : TWeakObjectPtr~APlayerController~
        + Binding : FGameplaySceneCaptureBinding
        + RuntimeOptions : FGameplaySceneCaptureRuntimeOptions
        + RenderContext : FGameplaySceneCaptureRenderContext
        + ChannelKey : FGameplaySceneCaptureChannelKey
        + FrameSerial : uint64
    }

    class FGameplaySceneCaptureChannelKey {
        + LocalPlayer : TObjectPtr~ULocalPlayer~
        + OutputChannelKey : FName
    }

    class FGameplaySceneCaptureChannel {
        + CaptureComponent : TObjectPtr~USceneCaptureComponent2D~
        + RenderTarget : TObjectPtr~UTextureRenderTarget2D~
        + Consumers : TArray~TWeakObjectPtr~UObject~~
        + ActiveHandle : FGameplaySceneCaptureHandle
        + FirstFrameFence : TSharedPtr~FRenderCommandFence~
    }

Manager 在可渲染的 Standalone、Client Game/PIE World 创建。本地 Session 不复制,Actor 请求可以经观看者 PlayerState 的可靠 Client RPC 路由到所属客户端再解析绑定。

会话调度与输出通道配置

捕获会话拥有播放进度,输出通道拥有捕获组件与纹理。两者通过通道键和活动句柄联系,调度配置独立决定何时提交下一帧。

1
2
3
4
5
6
enum class EGameplaySceneCaptureUpdatePolicy : uint8
{
Once,
FixedRate,
Manual,
};

Once 表示单次捕获策略,FixedRate 按目标频率取得调度机会,Manual 通过显式帧请求推进。它们描述提交帧的方式,资源保留时长与会话停止仍由各自的生命周期配置控制。

1
2
3
4
5
struct FGameplaySceneCaptureChannelKey
{
TObjectPtr<ULocalPlayer> LocalPlayer = nullptr;
FName OutputChannelKey = NAME_None;
};
1
2
3
4
5
6
7
8
9
struct FGameplaySceneCaptureScheduleConfig
{
EGameplaySceneCaptureUpdatePolicy UpdatePolicy = EGameplaySceneCaptureUpdatePolicy::FixedRate;
float TargetFPS = 20.0f;
int32 Priority = 100;
bool bPauseWithoutRegisteredConsumer = true;
bool bAllowCatchUpCaptures = false;
float ReleaseGraceSeconds = 10.0f;
};
1
2
3
4
5
struct FGameplaySceneCaptureActivationOptions
{
bool bOverrideDuration = false;
float DurationSeconds = 0.0f;
};

通道身份由 LocalPlayer 与 OutputChannelKey 共同组成,同名输出在不同本地视图中仍可隔离。会话停止后,通道可在 ReleaseGraceSeconds 窗口内保留资源供后续复用,消费者列表采用弱引用,不拥有消费者对象。

调度默认固定频率、目标 20 帧,Priority 用于预算竞争;无注册消费者时默认暂停,默认不追补积压捕获。覆盖播放时长需要显式打开 bOverrideDuration,不能仅凭 DurationSeconds 有值认定已生效。首次捕获提交与 FirstFrameReady 分别由帧状态和渲染栅栏确认,分配纹理本身不是首帧可用。

配方、Binding 与请求

配置资产按 CaptureKey 索引,Key 去除首尾空白,重复项按包名排序保留第一份。运行时读取资产,不读取作者 JSON。

配方描述分辨率、渲染参数、调度方式和寿命。Binding 描述这次具体使用的 Actor、Pawn、Anchor 或世界镜位;Anchor 提供完整镜位,不让 Widget 猜测位置。

网络请求返回 true 只代表请求已路由,本地广播成功也只代表存在监听者。需要使用激活结果与输出事件判断本地资源是否准备成功。

Session 与 Channel 仲裁

Handle 使用 Slot+Serial。Session 弱引用 Owner、观看者、RenderWorld 与 LifetimeOwner,任一失效、超时或显式停止都会结束实例。

Channel 身份为 (LocalPlayer, OutputChannelKey),同一通道同时只有一个活动 Session。新请求先比较 ChannelPriority:低值拒绝,高值替换,同值按新请求的 ConflictPolicy 处理。

替换先停止旧 Session,再准备新资源。因此新请求若随后失败,不会自动恢复旧会话。回调中若另一个请求已经占据通道,当前请求以 ChannelBusy 失败。

PlayerState 适配组件一次保存一个成功 Handle,会停止自己此前其它 Handle;直接使用 Manager 则可管理多个不同通道。

会话竞争与通道资源

Session 表示一次运行请求,Channel 表示共享输出位置。仲裁先决定请求是否取得通道,再建立本次资源绑定;通道缓存可以跨 Session 保留。

激活时验证捕获定义、观察者和渲染 World,在 ChannelKey 下建立会话并分配带代次的 Handle。RenderTarget 分配成功只说明输出资源存在;会话另用首帧状态和渲染栅栏判断内容何时可读。捕获执行由下面的统一调度器驱动。

替换先结束旧 Session,因此后续准备失败不恢复旧 Session。输出状态携带当前 Handle,Consumer 依据状态判断当前来源,不能依据缓存 RT 是否存在推断会话活跃。

资源复用与寿命

RT 描述相同则复用,变化才重建。停用后按 ReleaseGraceSeconds 与 HoldLastFrameSeconds 的较大值延迟释放缓存;跨 World 停止会立即销毁 CaptureComponent。

缓存仍在不代表 UI 继续显示。Consumer 收到停用后按自己的显示策略处理,不能仅用 RenderTarget 非空判断活跃。

Timed 寿命与渲染调度分开。没有 Consumer 可以暂停渲染,但寿命照常流逝;Once 捕获一次后保持 Session,Manual 等待明确请求,FixedRate 尝试达到目标频率。

预算调度

捕获组件关闭 Tick、CaptureEveryFrame 和 CaptureOnMovement,由 Manager 集中处理:

一轮更新依次处理失效绑定与寿命、首帧完成、到期捕获和通道回收。会话决定是否继续提交帧,Channel 负责 RenderTarget 与 Consumer,停止会话后两者的剩余寿命可以不同。

所有 Channel 共用硬预算,没有额外每秒像素预算,也不保证每个配方达到目标 FPS。RT 内存估算不包含完整场景渲染临时资源与 ViewState,实际 GPU 成本需要单独测量。

首帧就绪

sequenceDiagram
    participant U as 业务
    participant M as Manager
    participant R as 渲染
    participant C as Consumer
    U->>M: 激活通道
    M-->>C: Activated RT已分配
    M->>R: 预算允许后提交Capture
    R-->>M: 后续帧与Fence条件满足
    M-->>C: FirstFrameReady
    U->>M: 停止
    M-->>C: Deactivated

主世界使用 CaptureSceneDeferred;GamePreview 没有主视口消费延迟队列,预算通过后显式 CaptureScene。首帧至少等待下一游戏帧,外部预览还等待 RenderCommandFence。

Consumer 中途注册会补当前状态。输出包含 Handle、RT、有效分辨率、活跃与首帧位、FrameSerial、镜像选项、剩余秒数与 StopReason,UI 不需要窥探 Session 内部。

绑定变化与外部世界

捕获准备时验证 Binding,短暂失效可保留最后一帧并重试,超过窗口后停止。Once 已完成或 Manual 没有请求时,不会持续重新解析绑定。

ActivateOnCurrentPawn 可以在 PawnSet 后重建绑定;普通最终 Binding 请求不自动取得这一跟随语义。Rebind 请求相机切换,但不让已经完成的 Once 再捕获一次。

外部 PreviewWorld 的 Binding 与 ShowOnlyActors 必须属于 RenderWorld,Owner 与 ViewingPlayer 属于宿主 World。释放顺序是停止 Capture、销毁展示对象、释放 World。

捕获提交与可用输出

预算调度只决定何时提交捕获,首帧确认决定何时发布可用输出。Manager 先收集候选身份再回调,避免 Consumer 改变会话集合时使当前遍历失效。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
bool UGameplaySceneCaptureManager::RequestCaptureFrame(const FGameplaySceneCaptureHandle Handle)
{
FGameplaySceneCaptureSession* Session = FindSessionMutable(Handle);
if (Session == nullptr)
{
return false;
}

Session->bFrameRequested = true;
Session->NextCaptureTimeSeconds = GetWorld()->GetTimeSeconds();
return true;
}

void UGameplaySceneCaptureManager::ProcessDueCaptures(const double NowSeconds)
{
struct FDueCapture
{
FGameplaySceneCaptureHandle Handle;
int32 Priority = 0;
double DueTime = 0.0;
};

TArray<FDueCapture> DueCaptures;
DueCaptures.Reserve(ActiveSessionCount);
for (const FGameplaySceneCaptureSession& Session : Sessions)
{
if (!Session.bActive || !IsValid(Session.DataAsset))
{
continue;
}

const FGameplaySceneCaptureChannel* Channel = Channels.Find(Session.ChannelKey);
if (Channel == nullptr)
{
continue;
}

const FGameplaySceneCaptureScheduleConfig& Schedule =
Session.DataAsset->CaptureData.Schedule;
if (Schedule.bPauseWithoutRegisteredConsumer && !HasOutputConsumer(*Channel))
{
continue;
}

bool bDue = false;
switch (Schedule.UpdatePolicy)
{
case EGameplaySceneCaptureUpdatePolicy::Once:
bDue = Session.FrameSerial == 0 && NowSeconds >= Session.NextCaptureTimeSeconds;
break;
case EGameplaySceneCaptureUpdatePolicy::FixedRate:
bDue = NowSeconds >= Session.NextCaptureTimeSeconds;
break;
case EGameplaySceneCaptureUpdatePolicy::Manual:
bDue = Session.bFrameRequested && NowSeconds >= Session.NextCaptureTimeSeconds;
break;
default:
break;
}

if (bDue)
{
DueCaptures.Add({Session.Handle, Schedule.Priority, Session.NextCaptureTimeSeconds});
}
}

DueCaptures.Sort(
[](const FDueCapture& A, const FDueCapture& B)
{ return A.Priority == B.Priority ? A.DueTime < B.DueTime : A.Priority > B.Priority; });

const FGameplaySceneCaptureBudget Budget = GameplaySceneCaptureCVars::GetBudget();
const int32 MaxCaptures = Budget.MaxCapturesPerFrame;
const int64 MaxPixels = Budget.MaxPixelsPerFrame;
int32 CaptureCount = 0;
int64 CapturedPixels = 0;
for (const FDueCapture& DueCapture : DueCaptures)
{
if (CaptureCount >= MaxCaptures)
{
break;
}

const FGameplaySceneCaptureSession* Session = FindSession(DueCapture.Handle);
if (Session == nullptr)
{
continue;
}
const FGameplaySceneCaptureChannel* Channel = Channels.Find(Session->ChannelKey);
if (Channel == nullptr || !Channel->bHasEffectiveRenderTargetDesc)
{
continue;
}

const int64 Pixels = static_cast<int64>(Channel->EffectiveRenderTargetDesc.Resolution.X) *
static_cast<int64>(Channel->EffectiveRenderTargetDesc.Resolution.Y);
if (CapturedPixels + Pixels > MaxPixels)
{
continue;
}

if (CaptureSessionFrame(DueCapture.Handle, NowSeconds))
{
++CaptureCount;
CapturedPixels += Pixels;
}
}
}

Once 只安排首帧,FixedRate 依据下一次时间,Manual 还要求 bFrameRequested。排序先比较 Priority,再比较 DueTime;执行前重新解析 Handle 与 Channel,避免使用收集候选时的裸地址。像素预算以 int64 计算宽乘高,当前任务超预算时继续寻找后面的较小任务。只有 CaptureSessionFrame 成功才占用预算,次数上限则直接结束本轮。此策略没有额外的饥饿补偿,长期超预算的单次捕获需要调整描述或预算。

Once、Manual 和 FixedRate 改变调度条件,不改变资源所有权。Timed 寿命独立推进,没有 Consumer 时即使暂停渲染,也不会暂停实例寿命。停止后缓存释放策略与 UI 显示策略继续各自生效。

首帧可用与会话激活分开通知

创建 RenderTarget、激活会话和首帧可用是三个时间点。Manager 先收集已经提交捕获、尚未通知且进入后续游戏帧的 Handle,再逐项确认同步栅栏。核心派发段如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
for (const FGameplaySceneCaptureHandle Handle : ReadyHandles)
{
auto* Session = FindSessionMutable(Handle);
if (Session == nullptr)
continue;
auto* Channel = Channels.Find(Session->ChannelKey);
if (Channel == nullptr)
continue;

if (Channel->FirstFrameFence.IsValid() && !Channel->FirstFrameFence->IsFenceComplete())
continue;

Session->bFirstFrameReady = true;
NotifyFirstFrameReady(Session->ChannelKey,
BuildOutputState(Session->ChannelKey, *Channel, Session));
}

收集阶段要求 GFrameCounter > FirstCaptureSubmittedFrame,防止刚提交就在同一游戏帧宣布结果可用。若存在 FirstFrameFence,还需等待其完成。这个通知是框架的输出就绪契约,不代表已经执行像素回读或获得 CPU 图像副本。

通知前先设置 bFirstFrameReady,下一轮不会重复派发。工作列表只保存 Handle,派发前重新查找 Session 与 Channel,减少上一项通知停止会话后继续使用过期地址的风险。

通道替换也遵循类似边界:先比较优先级和同优先级冲突策略,停止旧会话后重新查询通道。如果停止回调已经创建了另一活动会话,当前申请返回 ChannelBusy,不再覆盖回调刚建立的新占用。

捕获队列与双预算调度

捕获请求只把会话标为待处理。Manager 先选出到期会话,再按优先级与时间排序,在每帧次数和像素预算内派发。

会话停止后延迟回收通道资源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void UGameplaySceneCaptureManager::ProcessChannelRelease(const double NowSeconds)
{
for (auto Iterator = Channels.CreateIterator(); Iterator; ++Iterator)
{
FGameplaySceneCaptureChannel& Channel = Iterator.Value();
PruneConsumers(Channel);
if (!Channel.ActiveHandle.IsValid() && Channel.ReleaseAtTimeSeconds >= 0.0 &&
NowSeconds >= Channel.ReleaseAtTimeSeconds)
{
ReleaseChannelResources(Channel);
}
if (!Channel.ActiveHandle.IsValid() && !HasOutputConsumer(Channel) &&
!IsValid(Channel.RenderTarget))
Iterator.RemoveCurrent();
}
}

通道资源只在没有 ActiveHandle 且宽限时间到达后释放;通道记录还要等消费者和 RenderTarget 都消失才从 Map 移除。保留通道与保留活动会话是两种生命周期,前者允许最后一帧或后续消费者继续使用已经建立的输出关系。